﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ThreeDWorld
{
    public class KeyFrameMesh : IDisposable
    {
        private VertexPositionNormalTexture[] _Vertices;
        private short[] _Indices;
        private DynamicVertexBuffer _VertexBuffer;

        public KeyFrameMesh(ContentReader reader)
        {
            Game = reader.Content.Game;

            _Indices = reader.ReadInt16Array();
            _Vertices = new VertexPositionNormalTexture[_Indices.Length];
            for (int i = 0; i != _Indices.Length; i++)
            {
                _Vertices[i].TextureCoordinate = reader.ReadVector2();
            }

            KeyFrames = new KeyFrame[reader.ReadInt32()];

            for (int i = 0; i != KeyFrames.Length; i++)
            {
                KeyFrames[i] = new KeyFrame(reader, _Indices);
            }

            _VertexBuffer = new DynamicVertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture), _Vertices.Length, BufferUsage.WriteOnly);
        }

        public Game Game
        {
            get;
            private set;
        }

        public GraphicsDevice GraphicsDevice
        {
            get { return Game.GraphicsDevice; }
        }

        public KeyFrame[] KeyFrames
        {
            get;
            private set;
        }

        public void Draw(int i, int j, float amount)
        {
            KeyFrame frame1 = KeyFrames[i];
            KeyFrame frame2 = KeyFrames[j];

            frame1.Lerp(frame2, _Vertices, _Indices, amount);

            _VertexBuffer.SetData<VertexPositionNormalTexture>(_Vertices);

            try
            {
                GraphicsDevice.SetVertexBuffer(_VertexBuffer);
                GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, _Indices.Length / 3);
            }
            finally
            {
                GraphicsDevice.SetVertexBuffer(null);
            }
        }

        public void Dispose()
        {
            if (!_VertexBuffer.IsDisposed)
            {
                _VertexBuffer.Dispose();
            }
        }
    }
}
